package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.TileUtils;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.FilteLayerPeopleAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.LayerGridInfoBean;
import com.mingtu.jgspatrol.bean.PeopleListLayer;
import com.mingtu.jgspatrol.databinding.ActivityChargeAreaMapBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class ChargeAreaMapActivity extends MyBaseActivity<ActivityChargeAreaMapBinding> {
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private LatLng location;
    private TileOverlayOptions tileOverlayOptions;
    private TileOverlay tileOverlay;
    private List<PeopleListLayer.DataBean> DataBean = new ArrayList<>();
    private FilteLayerPeopleAdapter filteLayerPeopleAdapter;
    private List<String> nameProgress = new ArrayList<>();
    private List<LatLng> allLatLngs = new ArrayList<>();
    private List<Polygon> polygonList = new ArrayList<>();
    private List<Polyline> polylineList = new ArrayList<>();
    private LinkedHashMap<Integer, List<PeopleListLayer.DataBean>> PeopleDataBean = new LinkedHashMap<>();
    private LinkedHashMap<Integer, List<LayerGridInfoBean.GridInfoBean>> GridInfoBeanMap = new LinkedHashMap<>();
    private int currentPosition = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_charge_area_map;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("林长网格");
        showTopRightImg(R.mipmap.icon_filte_white2);
    }

    @Override
    protected void initData() {
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        binding.recyclerPeople.setLayoutManager(flm1);

        filteLayerPeopleAdapter = new FilteLayerPeopleAdapter(context, DataBean);
        binding.recyclerPeople.setAdapter(filteLayerPeopleAdapter);
        filteLayerPeopleAdapter.setOnItemClickListener(new FilteLayerPeopleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                //每次请求前清除吊之前的数据
                allLatLngs.clear();
                for (Polygon polygon : polygonList) {
                    polygon.remove();
                }
                for (Polyline polyline : polylineList) {
                    polyline.remove();
                }
                List<PeopleListLayer.DataBean> DataBean = PeopleDataBean.get(currentPosition);
                PeopleListLayer.DataBean dataBean = DataBean.get(position);
                String name = dataBean.getName();
                String str = "";
                int level = dataBean.getLevel();
                if (level <= 4) {
                    nameProgress.add(name);
                    currentPosition = nameProgress.size();
                    getGridInfo(name);
                    getChildPeopleList(level, name);
                    filteLayerPeopleAdapter.upData(position);

                    for (int i = 0; i < nameProgress.size(); i++) {
                        String myName = nameProgress.get(i);
                        if (i < nameProgress.size() - 1) {
                            myName = myName + ">";
                        }
                        str += myName;
                    }

                    String myStr = "当前网格：" + str;
                    SpannableStringBuilder style = new SpannableStringBuilder(myStr);
                    style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), myStr.length() - name.length(), myStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    binding.tvPeopleProgress.setText(style);
                }
                if (level == 4) {
                    closeRightDrawers();
                }

                binding.tvBack.setVisibility(View.VISIBLE);
                binding.tvPeopleProgress.setVisibility(View.VISIBLE);

            }
        });
        addClickListener(this, binding.ivLocation, binding.tvBack, binding.tvReset);
    }

    @Override
    protected void getData() {
        String userName = SPStaticUtils.getString(SPTools.userName);
        getGridInfo(userName);
        getParentPeopleList();
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.setMapTextZIndex(1);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
//        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {


            }
        });


        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markerList.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }

        //自定义瓦片
        tileOverlayOptions = TileUtils.getTileOverlayOptions();
        tileOverlay = aMap.addTileOverlay(tileOverlayOptions);
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            binding.mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_location:
                if (location != null) {
                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(location));
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                }
                break;

            case R.id.tv_back:
                nameProgress.remove(nameProgress.size() - 1); //移除名字
                echoEvent(nameProgress);
                break;

            case R.id.tv_reset:
                nameProgress.clear();
                //PeopleDataBean  GridInfoBeanMap 的数据用于回显使用，此处不用清空，重置之后再次点击会覆盖Map的数据
                echoEvent(nameProgress);
                closeRightDrawers();

                break;
        }
    }


    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        boolean isShown = binding.layoutRightDrawer.isShown();
        if (isShown) {
            closeRightDrawers();
        } else {
            openRightDrawer();
        }

    }

    /**
     * 网格的总林长列表
     */
    private void getParentPeopleList() {
        OkGo.<String>post(MyConstant.POST_GRID_PARENT_PEOPLE)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            PeopleListLayer peopleListLayer = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                peopleListLayer = new PeopleListLayer();
                                peopleListLayer = gson.fromJson(result, PeopleListLayer.class);
                                List<PeopleListLayer.DataBean> dataBeans = peopleListLayer.getData();
                                if (dataBeans != null) {
                                    if (dataBeans.size() > 0) {
                                        DataBean.addAll(dataBeans);
                                        filteLayerPeopleAdapter.upData(DataBean);
                                        PeopleDataBean.put(0, dataBeans);
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 查询子人员列表
     */
    private void getChildPeopleList(int level, String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("level", level);
        hashMap.put("name", name);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_GRID_CHILD_PEOPLE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            PeopleListLayer peopleListLayer = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                peopleListLayer = new PeopleListLayer();
                                peopleListLayer = gson.fromJson(result, PeopleListLayer.class);
                                List<PeopleListLayer.DataBean> dataBeans = peopleListLayer.getData();
                                if (dataBeans != null) {
                                    if (dataBeans.size() > 0) {
                                        DataBean.clear();
                                        DataBean.addAll(dataBeans);
                                        filteLayerPeopleAdapter.upData(DataBean);
                                        PeopleDataBean.put(currentPosition, dataBeans);
                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 获取网格相关信息
     */
    private void getGridInfo(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_GRID_INFO2)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                LayerGridInfoBean layerGridInfoBean = new LayerGridInfoBean();
                                layerGridInfoBean = gson.fromJson(result, LayerGridInfoBean.class);
                                List<LayerGridInfoBean.GridInfoBean> gridInfoBeans = layerGridInfoBean.getGridInfo();
                                GridInfoBeanMap.put(currentPosition, gridInfoBeans);

                                gridInfoEvent(gridInfoBeans);


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 回显数据逻辑
     */
    private void echoEvent(List<String> nameProgress) {
        currentPosition = nameProgress.size();
        //获取到上级数据
        List<PeopleListLayer.DataBean> dataBeans = PeopleDataBean.get(currentPosition);
        filteLayerPeopleAdapter.upData(dataBeans);

        //网格数据
        List<LayerGridInfoBean.GridInfoBean> gridInfoBeans = GridInfoBeanMap.get(currentPosition);
        gridInfoEvent(gridInfoBeans);

        String str = "";
        String myName = "";
        for (int i = 0; i < nameProgress.size(); i++) {
            myName = nameProgress.get(i);
            if (i < nameProgress.size() - 1) {
                myName = myName + ">";
            }
            str += myName;
        }
        String myStr = "当前网格：" + str;
        SpannableStringBuilder style = new SpannableStringBuilder(myStr);
        style.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), myStr.length() - myName.length(), myStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        binding.tvPeopleProgress.setText(style);

        //判断返回的按钮显示条件
        if (nameProgress.size() > 0) {
            binding.tvBack.setVisibility(View.VISIBLE);
            binding.tvPeopleProgress.setVisibility(View.VISIBLE);
        } else {
            binding.tvBack.setVisibility(View.GONE);
            binding.tvPeopleProgress.setVisibility(View.GONE);
        }
    }


    /**
     * 网格显示逻辑
     */
    private void gridInfoEvent(List<LayerGridInfoBean.GridInfoBean> gridInfoBeans) {
        allLatLngs.clear();
        polygonList.clear();
        polygonList.clear();
        if (gridInfoBeans != null) {
            if (gridInfoBeans.size() > 0) {

                String myArea = "0";
                //责任区域及面积
                for (int j = 0; j < gridInfoBeans.size(); j++) {
                    LayerGridInfoBean.GridInfoBean gridInfoBean = gridInfoBeans.get(j);
                    BigDecimal area = new BigDecimal(gridInfoBean.getArea());
                    String points = gridInfoBean.getPoints().replaceAll(" ", "");
                    myArea = new BigDecimal(myArea).add(area).doubleValue() + "";

                    if (points.length() > 0) {
                        List<LatLng> latLngs = new ArrayList<>();
                        MyLogUtil.e("points", "points length=" + points.length() + "," + (points.length() - 3));
                        String MyPoints = points.substring(3, points.length() - 3);
                        if (MyPoints.indexOf("，") != -1) {
                            //含有中文符号的时候把中文逗号换成英文逗号
                            MyPoints = MyPoints.replaceAll("，", ",");
                        }
                        String[] objectsArray1 = MyPoints.split("],\\[");
                        for (int i = 0; i < objectsArray1.length; i++) {
                            String[] objectsArray2 = objectsArray1[i].split(",");
                            double lng = Double.parseDouble(objectsArray2[0]);
                            double lat = Double.parseDouble(objectsArray2[1]);
                            LatLng latLng = new LatLng(lat, lng);
                            latLngs.add(latLng);
                            allLatLngs.add(latLng);
                        }
                        PolygonOptions polygonOptions = new PolygonOptions();
                        polygonOptions.addAll(latLngs);
                        polygonOptions.strokeWidth(2);
                        polygonOptions.fillColor(context.getResources().getColor(R.color.bg_color_1f1e9));
                        polygonOptions.strokeColor(context.getResources().getColor(R.color.bg_color_1f1e9));
                        Polygon mapPolygon = aMap.addPolygon(polygonOptions);
                        polygonList.add(mapPolygon);


                        Polyline mapPolyline = aMap.addPolyline(new PolylineOptions()
                                .addAll(latLngs)
                                .width(8)
                                .zIndex(100)
                                .setDottedLine(true)
                                .setDottedLineType(PolylineOptions.DOTTEDLINE_TYPE_SQUARE)
                                .color(context.getResources().getColor(R.color.colorPrimary)));
                        polylineList.add(mapPolyline);
                    }

                }

                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(allLatLngs), 200));

                if (!StringUtils.isEmpty(myArea)) {
//                                                double myArea = Double.parseDouble(area) / 1000 * 1000;
                    BigDecimal b1 = new BigDecimal(myArea);
                    BigDecimal b2 = new BigDecimal((1000 * 1000) + "");

//                                            tvArea.setText(b1.divide(b2, 2) + "k㎡");
                }
            }
        }
    }


    /**
     * 关闭右侧边栏
     */
    private void closeRightDrawers() {
        binding.layoutDrawerPeople.closeDrawer(binding.layoutRightDrawer);
    }

    /**
     * 打开右侧边栏
     */
    private void openRightDrawer() {
        binding.layoutDrawerPeople.openDrawer(binding.layoutRightDrawer);
    }

}